<?php declare(strict_types=1);

namespace Zyucv7\Core\Database\Driver;

use PDO;
use Zyucv7\Core\Database\Driver AS DatabaseDriver;
use Zyucv7\Core\Database\DatabaseException;

class Sqlite extends DatabaseDriver
{

    /**
     * 构造函数
     * @param string $host 数据库主机
     * @param string $dbname 数据库名
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $charset 字符集，默认utf8mb4
     * @throws PDOException
     */
    public function __construct($config)
    {
        $this->config = $config;
        $this->connect();
    }

    private function connect(): void
    {
        $dbPath = $this->config['database'] ?? '';
        if (empty($dbPath)) {
            throw DatabaseException::InvalidArgument("Database name is required.");
        }
        if(!file_exists($dbPath)) {
            throw DatabaseException::InvalidArgument("Database file does not exist: {$dbPath}");
        }
        $dsn = "sqlite:{$dbPath}";
        try {
            $this->pdo = new PDO($dsn, null, null, $this->options);
        } catch (\PDOException $e) {
            throw DatabaseException::Pdo($e->getMessage());
        }
    }
    
}
